package com.gzhryc.shared_device.oem.h5.mng.controllers.sys;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.DefaultEnum;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.CheckErrorException;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.mng.dto.sys.ManagerData;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.system.ManagerService;
import com.gzhryc.system.RoleService;
import com.gzhryc.system.dao.db.Manager;
import com.gzhryc.system.dao.db.Role;
import com.gzhryc.system.dao.enums.ManagerEnum;
import com.gzhryc.system.dao.models.ManagerRoleInfo;
import com.gzhryc.system.dto.ManagerSearch;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 后台管理员相关HTTP接口
 *
 * @author 张浩
 * @version 2016-9-1
 */
public class ManagerController {

    @Route("/sys/manager/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("typeList", ManagerEnum.Type.values());
        request.setAttribute("statusList", DefaultEnum.Status.values());
        return "/sys/manager/list.html";
    }

    @Route("/sys/manager/list.data")
    public ListResult<ManagerData> listData(HttpServletRequest request) {
        ListResult<ManagerData> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");
        ManagerSearch search = WebUtils.getParameter(request, ManagerSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(ManagerService.self().countBySearch(search));
        List<Manager> managerList = ManagerService.self().findBySearch(search, pageNo, pageLimit);
        if(managerList != null && managerList.size() > 0){
            result.setCode(DtoConstants.SUCCESS,null);
            result.getBody().setData(new ArrayList<>());

            List<Long> managerIds = new ArrayList<>();
            for(Manager manager : managerList){
                managerIds.add(manager.getId());
            }
            List<ManagerRoleInfo> ManagerRoleInfoList = ManagerService.self().findRoleInfoByManagerIds(managerIds);
            for(Manager manager : managerList) {
                ManagerData item = ClassTools.copy(new ManagerData(),manager);
                if (ManagerRoleInfoList != null && ManagerRoleInfoList.size() > 0){
                    for(ManagerRoleInfo managerRoleNames : ManagerRoleInfoList){
                        if(manager.getId().equals(managerRoleNames.getManagerId())){
                            item.setRoleIds(managerRoleNames.getRoleIds());
                            item.setRoleNames(managerRoleNames.getRoleNames());
                            break;
                        }
                    }
                }
                result.getBody().getData().add(item);
            }
        }
        return result;
    }

    @Route("/sys/manager/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        ManagerSearch search = new ManagerSearch();
        search.setName(term);
        search.setStatus(DefaultEnum.Status.Usable.index());

        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(ManagerService.self().countBySearch(search));
        List<Manager> list = ManagerService.self().findBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (Manager manager : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(manager.getId().toString());
                item.setText(manager.getName());
                result.getBody().getData().add(item);
            }
        }
        return result;
    }

    @Route(value = "/sys/manager/add.html", method = "get")
    public String add(HttpServletRequest request) {
        return "/sys/manager/edit.html";
    }

    @Route(value = "/sys/manager/update.html", method = "get")
    public String update(HttpServletRequest request, HttpServletResponse response) {
        Long id = WebUtils.getLong(request, "id");
        if (id != null) {
            Manager manager = ManagerService.self().getById(id);
            if (manager != null) {
                WebUtils.setAttribute(request, manager);
                List<Role> roles = RoleService.self().findByManagerId(manager.getId());
                if (roles != null) {
                    List<Long> ids = new ArrayList<Long>();
                    for (Role role : roles) {
                        ids.add(role.getId());
                    }
                    request.setAttribute("roles", StringUtils.join(ids, ","));
                }
            }
        }
        return "/sys/manager/edit.html";
    }

    @Route(value = "/sys/manager/add.do", method = "post")
    public AjaxResult doAdd(HttpServletRequest request, HttpServletResponse response) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败");
        try {
            Manager manager = WebUtils.getParameter(request, Manager.class);
            ValidateTools.check(manager);
            String roleStr = WebUtils.getString(request, "roles");
            List<Long> roles = StringTools.split2Long(roleStr, ",");
            if (ManagerService.self().register(manager, roles)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (CheckErrorException e) {
            result.setMsg(e.getMessage());
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = "/sys/manager/update.do", method = "post")
    public AjaxResult doUpdate(HttpServletRequest request, HttpServletResponse response) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败");
        try {
            Manager manager = WebUtils.getParameter(request, Manager.class);
            ValidateTools.check(manager);
            String roleStr = WebUtils.getString(request, "roles");
            List<Long> roles = StringTools.split2Long(roleStr, ",");
            if (ManagerService.self().updateInfo(manager, roles)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (CheckErrorException e) {
            result.setMsg(e.getMessage());
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/sys/manager/changeStatus.do")
    public AjaxResult changeStatus(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败");
        Long id = WebUtils.getLong(request, "id");
        if (id != null) {
            if (ManagerService.self().changeStatus(id)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route("/sys/manager/del.do")
    public AjaxResult delete(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败");
        Long id = WebUtils.getLong(request, "id");
        if (id != null) {
            try {
                if (ManagerService.self().deleteById(id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        } else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route(value = "/sys/manager/resetPwd.do", method = "post")
    public AjaxResult resetPwd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "重置失败");
        Long id = WebUtils.getLong(request, "id");
        String loginPwd = request.getParameter("pwd");
        if (id != null && StringUtils.isNotBlank(loginPwd)) {
            if (ManagerService.self().resetPwd(id, loginPwd)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        }
        return result;
    }
}
